package cl.foursoft.sirvicod.service;

import java.sql.Connection;

import cl.foursoft.sirvicod.dao.facade.FacadeDepartamento;
import cl.foursoft.sirvicod.dao.implementacion.DBMannager;
import cl.foursoft.sirvicod.dao.transferObject.DepartamentoTO;
import cl.foursoft.sirvicod.util.UtilLog;

public class DepartamentoService {
	
	public DepartamentoTO obtenerDepartamento(int numeroDepto){
		Connection c = DBMannager.getConnection();
		FacadeDepartamento facadeDepto = new FacadeDepartamento();		
		DepartamentoTO resp = null;
		
		try {
			
			resp = facadeDepto.obtenerDepartamento(numeroDepto, c);
			
			boolean exito = (resp != null);			
			DBMannager.close(c, exito);
		}
		catch (Exception ex) 
		{
			UtilLog.registrar(ex);
			DBMannager.closeOnError(c);
		}
		return resp;
	}
	
	public int guardarDepartamento(DepartamentoTO depto){
		Connection c = DBMannager.getConnection();
		FacadeDepartamento facadeDepto = new FacadeDepartamento();		
		int resp = -1;
		
		try {
			if(facadeDepto.existeDepartamento(depto.getNumeroDepto(), c)){
				//Actualizar departamento
				resp = facadeDepto.actualizarDepartamento(depto, c);
			}
			else{
				//Guardar nuevo departamento
				resp = facadeDepto.guardarDepartamento(depto, c);
			}
			
			boolean exito = (resp != -1);			
			DBMannager.close(c, exito);
		}
		catch (Exception ex) 
		{
			UtilLog.registrar(ex);
			DBMannager.closeOnError(c);
		}
		return resp;
	}
}
